/*
 *  imageCropper.cpp
 *  Ball and Plate
 *
 *  Created by Kenn Sebesta on 2007-11-25.
 *  Copyright 2007 __MyCompanyName__. All rights reserved.
 *
 */

#include "imageCropper.h"


void imageCropper( CvRect *cropRect, CvMat *y_measrd, CvRect limitR, int viewSize, int missingCount, int ballGone )
{	
	int viewSizeX, viewSizeY;
	double cropIncreaseSpeed=4.0;
	
	if ( ballGone==0 && missingCount<=0 ){
		//This function crops the image around the ball. The window is centered on the ball and
		//has a width and height of viewSize.
		cropRect->x=cvFloor(cvmGet( y_measrd, 0, 0 ))-viewSize/2;
		cropRect->y=cvFloor(cvmGet( y_measrd, 1, 0 ))-viewSize/2;
	}
	else if (ballGone ==0){
		//Haven't found the ball? Make the crop larger.
		viewSize+=(int)(2*missingCount*cropIncreaseSpeed);
		cropRect->x=cvFloor(cvmGet( y_measrd, 0, 0 ))-viewSize/2;
		cropRect->y=cvFloor(cvmGet( y_measrd, 1, 0 ))-viewSize/2;
		
	}
	else{ //Still haven't found it? Reset the crop.
		*cropRect=cvRect( limitR.x, limitR.y, limitR.width, limitR.height );
		return;
	}
	
	// Make sure the crop stays in the image.
	viewSizeX=viewSizeY=viewSize;
	if (cropRect->x < limitR.x) { //If the window leaves the top, we hard set it to the top edge
		cropRect->x=limitR.x;
	}
	if (cropRect->y < limitR.y) { //If the window leaves the left side, we hard set it to the left side edge
		cropRect->y=limitR.y;
	}
	if ((cropRect->x+viewSize) > ( limitR.x+limitR.width)) { //If the window leaves the bottom, we hard set it to the bottom edge
		cropRect->x=limitR.x+limitR.width-viewSize;
	}
	
	if ((cropRect->y+viewSize) > ( limitR.y+limitR.height )) { //If the window leaves the right side, we hard set it to the right side edge
		cropRect->y=limitR.y+limitR.height-viewSize;
	}	
	
	cropRect->width=viewSizeY;
	cropRect->height=viewSizeX;

	return;
}
